﻿@page "/account/reset-password"
@using CleanArchitecture.Blazor.Domain.Identity
@using System.Text
@using Microsoft.AspNetCore.WebUtilities
@using System.ComponentModel.DataAnnotations


@inherits OwningComponentBase
@inject IStringLocalizer<ResetPassword> L
@inject ILogger<ResetPassword> Logger
<PageTitle>@Title</PageTitle>

<EditForm Model="Input" FormName="resetpassword" OnValidSubmit="OnValidSubmitAsync" method="post">
    <DataAnnotationsValidator/>
    <MudText Typo="Typo.h4" GutterBottom="true">@Title</MudText>
    <MudText Typo="Typo.body1">@L["Please enter your new password below. Ensure your password is strong and memorable."]</MudText>
    <StatusMessage Message="@message" Error="true"/>
    <input type="hidden" name="Input.Token" value="@Input.Token"/>
    <input type="hidden" name="Input.UserId" value="@Input.UserId"/>
    <MudTextField @bind-Value="Input.Password"
                  For="@(() => Input.Password)"
                  InputType="@(_showPassword ? InputType.Text : InputType.Password)"
                  Label="@L["New Password"]"
                  Placeholder="Enter your new password"
                  Variant="Variant.Outlined"
                  Class="my-4"
                  Required="true"
                  Adornment="Adornment.End"
                  AdornmentIcon="@(_showPassword ? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
                  OnAdornmentClick="TogglePasswordVisibility" />
    <MudTextField @bind-Value="Input.ConfirmPassword"
                  For="@(() => Input.ConfirmPassword)"
                  InputType="@(_showConfirmPassword ? InputType.Text : InputType.Password)"
                  Label="@L["Confirm New Password"]"
                  Placeholder="Re-enter your new password"
                  Variant="Variant.Outlined"
                  Class="my-4"
                  Required="true"
                  Adornment="Adornment.End"
                  AdornmentIcon="@(_showConfirmPassword ? Icons.Material.Filled.Visibility : Icons.Material.Filled.VisibilityOff)"
                  OnAdornmentClick="ToggleConfirmPasswordVisibility" />

    <MudButton Variant="Variant.Filled"
               Color="Color.Primary"
               Size="Size.Large"
               ButtonType="ButtonType.Submit"
               FullWidth="true">
        <MudText>@L["Reset Password"]</MudText>
    </MudButton>
</EditForm>


@code {
    public const string PageUrl = "/account/reset-password";
    public string Title = "Reset Your Password";
    private UserManager<ApplicationUser> _userManager = null!;
    private bool _showPassword = false;
    private bool _showConfirmPassword = false;

    [SupplyParameterFromQuery(Name = "token")]
    public string? Token { get; set; }

   
    [SupplyParameterFromQuery(Name = "userid")]
    public string? UserId { get; set; }

    public InputModel Input { get; set; } = new();
    private string Password { get; set; } = string.Empty;

    private string message = string.Empty; 

    private void TogglePasswordVisibility()
    {
        _showPassword = !_showPassword;
    }

    private void ToggleConfirmPasswordVisibility()
    {
        _showConfirmPassword = !_showConfirmPassword;
    }

    protected override Task OnInitializedAsync()
    {
        Title = L["Reset Your Password"];
        _userManager = ScopedServices.GetRequiredService<UserManager<ApplicationUser>>();
        if (Token is null || UserId is null)
        {
            var message = L["Invalid password reset link. Please try again."];
            return Task.CompletedTask;
        }

        Input.Token = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(Token));
        Input.UserId = UserId;
        return base.OnInitializedAsync();
    }

    private async Task OnValidSubmitAsync()
    {
        var user = await _userManager.FindByIdAsync(Input.UserId);
        if (user is null)
        {
            message = L["User not found. Please check the link and try again."];
            return;
        }

        var result = await _userManager.ResetPasswordAsync(user, Input.Token, Input.Password);
        if (!result.Succeeded)
        {
            message = L["There was an error resetting your password. Please try again."];
            Logger.LogError("Error resetting password for user {UserId}: {Errors}", user.Id, string.Join(", ", result.Errors.Select(e => e.Description)));
            return;
        }
        else
        {
            Navigation.NavigateTo(ResetPasswordConfirmation.PageUrl);
        }
    }


    public sealed class InputModel
    {
        [Required] public string UserId { get; set; } = "";

        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Required]
        public string Password { get; set; } = "";

        [Required]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match")]
        public string ConfirmPassword { get; set; } = "";

        [Required] public string Token { get; set; } = "";
    }

}